package com.teach.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import com.teach.service.ConfigService;
import com.teach.service.impl.ConfigServiceImpl;

@WebListener
public class MyListener implements HttpSessionListener,ServletContextListener{
	
	private int count = 0;
	private int online = 0;
	private ServletContext application;
	private ConfigService configService = new ConfigServiceImpl();
	
	@Override
	public void contextInitialized(ServletContextEvent arg0) {
		
		count = configService.getCount();
		System.out.println("configService初始化得到的count="+count);
		application = arg0.getServletContext();
		application.setAttribute("count", count);
		application.setAttribute("online", online);
		
	}
	

	@Override
	public void sessionCreated(HttpSessionEvent arg0) {
		count ++;
		online ++;
		System.out.println("sessionCreated里的自增count="+count);
		System.out.println("sessionCreated里的自增online="+online);
		application.setAttribute("count", count);
		application.setAttribute("online", online);
		
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent arg0) {
		online --;
		application.setAttribute("online", online);
	}

	@Override
	public void contextDestroyed(ServletContextEvent arg0) {
	
		configService.saveCount(count);
		
	}

	

}
